<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 工资统计管理
 */
class Wage extends Backend
{
    protected $model = null;
    protected $noNeedRight = ['index'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Report;
        
        // 设置JS文件
        $this->view->assign('js', ['backend/scanwork/wage']);
    }

    /**
     * 工资统计列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filterArr = (array)json_decode($filter, true);
            $filterArr = $filterArr ? $filterArr : [];
            
            $op = $this->request->get("op", '', 'trim');
            $opArr = (array)json_decode($op, true);
            $opArr = $opArr ? $opArr : [];
            
            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
            $order = $this->request->get("order", "DESC");
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 10);
            
            // 构建基础查询
            $list = $this->model
                ->with([
                    'allocation' => function($query) {
                        $query->with(['order', 'model.product', 'process']);
                    },
                    'user'
                ]);
            
            // 处理搜索参数
            foreach ($filterArr as $field => $value) {
                if ($value === '' || $value === null) {
                    continue;
                }
                
                $op = isset($opArr[$field]) ? $opArr[$field] : '=';
                
                switch ($field) {
                    case 'user.nickname':
                        // 员工姓名搜索 - 通过user_id关联
                        $userIds = \app\common\model\User::where('nickname', 'like', '%' . $value . '%')->column('id');
                        if (!empty($userIds)) {
                            $list = $list->where('user_id', 'in', $userIds);
                        } else {
                            // 如果没有找到匹配的用户，返回空结果
                            $list = $list->where('id', '=', 0);
                        }
                        break;
                    case 'createtime':
                        // 报工时间范围搜索 - FastAdmin 发送的是字符串格式
                        if ($op === 'RANGE') {
                            // 处理时间范围，格式可能是 "2025-09-01 00:00:00 - 2025-09-01 23:59:59"
                            if (strpos($value, ' - ') !== false) {
                                $dates = explode(' - ', $value);
                                if (count($dates) == 2) {
                                    $startTime = strtotime(trim($dates[0]));
                                    $endTime = strtotime(trim($dates[1]));
                                    if ($startTime && $endTime) {
                                        $list = $list->where('createtime', 'between', [$startTime, $endTime]);
                                    }
                                }
                            }
                        } else {
                            // 其他操作符
                            $list = $list->where('createtime', $op, $value);
                        }
                        break;
                    case 'status':
                        // 状态搜索
                        $list = $list->where('status', '=', intval($value));
                        break;
                    default:
                        // 直接字段搜索
                        if (in_array($field, ['id', 'user_id', 'allocation_id'])) {
                            if ($op === 'LIKE') {
                                $list = $list->where($field, 'like', '%' . $value . '%');
                            } else {
                                $list = $list->where($field, $op, $value);
                            }
                        }
                        break;
                }
            }
            
            // 正确计算分页
            if ($limit > 0) {
                $page = ceil(($offset + 1) / $limit);
                $list = $list->order($sort, $order)->paginate($limit, false, ['page' => $page]);
            } else {
                $list = $list->order($sort, $order)->paginate(10);
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        
        return $this->view->fetch();
    }

    /**
     * 工资统计汇总
     */
    public function summary()
    {
        if ($this->request->isAjax()) {
            $startDate = $this->request->get('start_date', date('Y-m-01'));
            $endDate = $this->request->get('end_date', date('Y-m-d'));
            $userId = $this->request->get('user_id', '');
            
            $where = [];
            $where[] = ['status', '=', 1]; // 只统计已确认的报工
            $where[] = ['createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')]];
            
            if ($userId && $userId !== '') {
                $where[] = ['user_id', '=', intval($userId)];
            }
            
            // 按员工分组统计
            $summary = $this->model
                ->with(['user'])
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')]);
            
            if ($userId && $userId !== '') {
                $summary = $summary->where('user_id', intval($userId));
            }
            
            $summary = $summary->field('user_id, SUM(quantity) as total_quantity, SUM(wage) as total_wage, COUNT(*) as report_count')
                ->group('user_id')
                ->select();
            
            // 计算总计
            $totalQuantity = 0;
            $totalWage = 0;
            $totalCount = 0;
            
            foreach ($summary as $item) {
                $totalQuantity += $item['total_quantity'];
                $totalWage += $item['total_wage'];
                $totalCount += $item['report_count'];
            }
            
            $result = [
                'summary' => $summary,
                'total' => [
                    'quantity' => $totalQuantity,
                    'wage' => $totalWage,
                    'count' => $totalCount
                ]
            ];
            
            $this->success('', null, $result);
        }
        
        // 设置JS文件
        $this->view->assign('js', ['backend/scanwork/wage']);
        return $this->view->fetch();
    }

    /**
     * 工资趋势图表
     */
    public function chart()
    {
        if ($this->request->isAjax()) {
            $startDate = $this->request->get('start_date', date('Y-m-01'));
            $endDate = $this->request->get('end_date', date('Y-m-d'));
            $userId = $this->request->get('user_id', '');
            
            $where = [];
            $where[] = ['status', '=', 1]; // 只统计已确认的报工
            $where[] = ['createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')]];
            
            if ($userId && $userId !== '') {
                $where[] = ['user_id', '=', intval($userId)];
            }
            
            // 按日期分组统计
            $dailyData = $this->model
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')]);
            
            if ($userId && $userId !== '') {
                $dailyData = $dailyData->where('user_id', intval($userId));
            }
            
            $dailyData = $dailyData->field('DATE(FROM_UNIXTIME(createtime)) as date, SUM(quantity) as quantity, SUM(wage) as wage')
                ->group('DATE(FROM_UNIXTIME(createtime))')
                ->order('date ASC')
                ->select();
            
            // 按员工分组统计
            $userData = $this->model
                ->with(['user'])
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')])
                ->field('user_id, SUM(wage) as total_wage')
                ->group('user_id')
                ->select();
            
            // 按工序分组统计
            $processData = $this->model
                ->with(['allocation.process'])
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')])
                ->field('allocation_id, SUM(wage) as total_wage')
                ->group('allocation_id')
                ->select();
            
            $dates = [];
            $quantities = [];
            $wages = [];
            
            foreach ($dailyData as $item) {
                $dates[] = $item['date'];
                $quantities[] = intval($item['quantity']);
                $wages[] = floatval($item['wage']);
            }
            
            // 处理员工数据
            $users = [];
            foreach ($userData as $item) {
                $users[] = [
                    'value' => floatval($item['total_wage']),
                    'name' => $item['user']['nickname'] ?? '未知员工'
                ];
            }
            
            // 处理工序数据
            $processes = [];
            $processWages = [];
            foreach ($processData as $item) {
                if ($item['allocation'] && $item['allocation']['process']) {
                    $processes[] = $item['allocation']['process']['name'];
                    $processWages[] = floatval($item['total_wage']);
                }
            }
            
            $result = [
                'dates' => $dates,
                'quantities' => $quantities,
                'wages' => $wages,
                'users' => $users,
                'processes' => $processes,
                'processWages' => $processWages
            ];
            
            $this->success('', null, $result);
        }
        
        // 设置JS文件
        $this->view->assign('js', ['backend/scanwork/wage']);
        return $this->view->fetch();
    }

    /**
     * 导出明细
     */
    public function export()
    {
        // 获取搜索参数
        $startDate = $this->request->get('start_date', '');
        $endDate = $this->request->get('end_date', '');
        $userId = $this->request->get('user_id', '');
        $status = $this->request->get('status', '');
        
        // 构建基础查询
        $list = $this->model
            ->with([
                'allocation' => function($query) {
                    $query->with(['order', 'model.product', 'process']);
                },
                'user'
            ]);
        
        // 时间范围筛选
        if ($startDate && $endDate) {
            $startTime = strtotime($startDate);
            $endTime = strtotime($endDate . ' 23:59:59');
            if ($startTime && $endTime) {
                $list = $list->where('createtime', 'between', [$startTime, $endTime]);
            }
        }
        
        // 员工筛选
        if ($userId && $userId !== '') {
            $list = $list->where('user_id', '=', intval($userId));
        }
        
        // 状态筛选
        if ($status !== '') {
            $list = $list->where('status', '=', intval($status));
        }
        
        // 获取所有数据（不分页）
        $list = $list->order('id', 'desc')->select();
        
        $filename = '工资明细_' . date('Y-m-d') . '.csv';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $fp = fopen('php://output', 'w');
        
        // 输出CSV头部
        $headers = ['ID', '员工姓名', '订单号', '产品名称', '型号名称', '工序名称', '报工数量', '计件工资', '状态', '报工时间', '备注'];
        fputcsv($fp, $headers);
        
        foreach ($list as $item) {
            $row = [
                $item['id'],
                $item['user']['nickname'] ?? '-',
                $item['allocation']['order']['order_no'] ?? '-',
                $item['allocation']['model']['product']['name'] ?? '-',
                $item['allocation']['model']['name'] ?? '-',
                $item['allocation']['process']['name'] ?? '-',
                $item['quantity'],
                $item['wage'],
                $this->getStatusText($item['status']),
                date('Y-m-d H:i:s', $item['createtime']),
                $item['remark'] ?? ''
            ];
            fputcsv($fp, $row);
        }
        
        fclose($fp);
        exit;
    }

    /**
     * 导出页面
     */
    public function exportPage()
    {
        // 设置JS文件
        $this->view->assign('js', ['backend/scanwork/wage_export']);
        return $this->view->fetch('export');
    }

    /**
     * 数据预览
     */
    public function preview()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        $userId = $this->request->get('user_id', '');
        $status = $this->request->get('status', '');
        
        // 构建查询条件
        $list = $this->model;
        
        // 时间范围筛选
        if ($startDate && $endDate) {
            $startTime = strtotime($startDate);
            $endTime = strtotime($endDate . ' 23:59:59');
            if ($startTime && $endTime) {
                $list = $list->where('createtime', 'between', [$startTime, $endTime]);
            }
        }
        
        // 员工筛选
        if ($userId && $userId !== '') {
            $list = $list->where('user_id', '=', intval($userId));
        }
        
        // 状态筛选
        if ($status !== '') {
            $list = $list->where('status', '=', intval($status));
        }
        
        // 统计信息
        $totalCount = $list->count();
        $totalQuantity = $list->sum('quantity');
        $totalWage = $list->sum('wage');
        $confirmedCount = $list->where('status', '=', 1)->count();
        
        $result = [
            'total_count' => $totalCount,
            'total_quantity' => $totalQuantity,
            'total_wage' => $totalWage,
            'confirmed_count' => $confirmedCount
        ];
        
        $this->success('', null, $result);
    }

    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        $statusMap = [
            0 => '待确认',
            1 => '已确认',
            2 => '已拒绝'
        ];
        return $statusMap[$status] ?? '未知';
    }

    /**
     * 导出汇总数据
     */
    public function exportSummary()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        $userId = $this->request->get('user_id', '');
        $status = $this->request->get('status', '1'); // 默认只导出已确认的
        
        // 构建查询条件
        $list = $this->model->with(['user']);
        
        // 状态筛选
        if ($status !== '') {
            $list = $list->where('status', '=', intval($status));
        }
        
        // 时间范围筛选
        if ($startDate && $endDate) {
            $startTime = strtotime($startDate);
            $endTime = strtotime($endDate . ' 23:59:59');
            if ($startTime && $endTime) {
                $list = $list->where('createtime', 'between', [$startTime, $endTime]);
            }
        }
        
        // 员工筛选
        if ($userId && $userId !== '') {
            $list = $list->where('user_id', '=', intval($userId));
        }
        
        // 按员工分组统计
        $summary = $list->field('user_id, SUM(quantity) as total_quantity, SUM(wage) as total_wage, COUNT(*) as report_count')
            ->group('user_id')
            ->select();
        
        $filename = '工资汇总_' . date('Y-m-d') . '.csv';
        
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        // 输出CSV头部
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        echo "员工姓名,总报工数量,总工资金额,报工次数,平均工价,统计期间\n";
        
        foreach ($summary as $item) {
            $avgWage = $item['total_quantity'] > 0 ? $item['total_wage'] / $item['total_quantity'] : 0;
            $period = $startDate . ' 至 ' . $endDate;
            
            echo sprintf(
                "%s,%d,%.2f,%d,%.2f,%s\n",
                $item['user']['nickname'] ?? '未知员工',
                $item['total_quantity'],
                $item['total_wage'],
                $item['report_count'],
                $avgWage,
                $period
            );
        }
        
        exit;
    }
} 